//
//  ScriptsAppliance.m
//  Scripts
//
//  Created by Thomas Cool on 6/2/08.
//  Copyright 2008 
//

#import "ScriptsAppliance.h"


@implementation ScriptsAppliance
// Override to allow FrontRow to load custom appliance plugins
+ (NSString *) className {
    // this function creates an NSString from the contents of the
    // struct objc_class, which means using this will not call this
    // function recursively, and it'll also return the *real* class
    // name.
    NSString * className = NSStringFromClass( self );
	
	// new method based on the BackRow NSException subclass, which conveniently provides us a backtrace
	// method!
	NSRange result = [[BRBacktracingException backtrace] rangeOfString:@"(in BackRow)"];
	
	if(result.location != NSNotFound) {
		NSLog(@"+[%@ className] called for whitelist check, so I'm lying, m'kay?", className);
		className = @"RUIDVDAppliance";
	}
	
	return className;
}
- (id)controllerForIdentifier:(id)identifier
{
	
//This is something else i was playing with: getting the screen to show up not matter what was selected if it was hidden going to make it different
	
	/*NSError *error;
	NSString *dataFilePath = @"/Users/frontrow/Documents/Scripts/visibility.txt";
	NSString *visibility = [NSString stringWithContentsOfFile:dataFilePath encoding:NSUTF8StringEncoding error:&error];
	if([visibility isEqualToString:@"no"])
	{
		[[NSNotificationCenter defaultCenter] postNotificationName: @"BRDisplayManagerResumeRenderingNotification" object: [BRDisplayManager sharedInstance]];
		[[BRDisplayManager sharedInstance] captureAllDisplays];
		visibility = @"yes";
		[visibility writeToFile:dataFilePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
	}*/
	
	
	//This is going to be the downloader for Mouse Locator once i figure out how to use a progress bar in ATV2.0
	
	/*if([identifier isEqualToString:@"scripts-option5"])
	{
		NSURL *theurl = [NSURL URLWithString:@"http://homepage.mac.com/douglasn/MouseLocator.dmg"];
		NSString *yesOrNo=@"yes";
		yesOrNo=[self scriptsDownloader:theurl];
		BRAlertController *alert = [BRAlertController alertOfType:0
														   titled:yesOrNo
													  primaryText:@"theurl"
													secondaryText:nil];
		return alert;
	}*/
	
	if([identifier isEqualToString:@"scripts-option4"])
	{		
		if([visibility isEqualToString:@"no"])
		{
			[[NSNotificationCenter defaultCenter] postNotificationName: @"BRDisplayManagerResumeRenderingNotification" object: [BRDisplayManager sharedInstance]];
			[[BRDisplayManager sharedInstance] captureAllDisplays];
			visibility = @"yes";
			if ([killbool isEqualToString:@"yes"]){
				if([MLAgent isEqualToString:@"yes"])
				{
					[NSTask launchedTaskWithLaunchPath:@"/usr/bin/killall" arguments:[NSArray arrayWithObjects:@"MouseLocatorAgent", nil]];
					MLAgent = @"no";
				}
			}
			else
			{
				NSString *killPath = @"/usr/bin/killall";
				NSFileManager *manager = [NSFileManager defaultManager];
			
				if ([manager fileExistsAtPath:killPath])
				{
					killbool =@"yes";
				}
				else
				{
					[NSTask launchedTaskWithLaunchPath:@"/bin/bash" arguments:[NSArray arrayWithObjects:@"/System/Library/CoreServices/Finder.app/Contents/Plugins/scripts.frappliance/Contents/Resources/killallinst.sh", nil]];
					killbool=@"yes";
				}
				if([MLAgent isEqualToString:@"yes"])
				{
					[NSTask launchedTaskWithLaunchPath:@"/usr/bin/killall" arguments:[NSArray arrayWithObjects:@"MouseLocatorAgent", nil]];
				}
			}
			
		}
		else
		{
			[[BRDisplayManager sharedInstance] releaseAllDisplays];
			visibility =@"no";
			[[NSNotificationCenter defaultCenter] postNotificationName: @"BRDisplayManagerStopRenderingNotification" object: [BRDisplayManager sharedInstance]];
			NSString *fontPath = @"Users/frontrow/Library/PreferencePanes/MouseLocator.prefPane";
			NSFileManager *manager = [NSFileManager defaultManager];
			if ([manager fileExistsAtPath:fontPath])
			{
				[[NSWorkspace sharedWorkspace] launchApplication:@"~/Library/PreferencePanes/MouseLocator.prefPane/Contents/Resources/MouseLocatorAgent.app"];
				MLAgent = @"yes";
			}
			BRAlertController *alert = [BRAlertController alertOfType:0
															   titled:@"Bye Bye"
														  primaryText:nil
														secondaryText:nil];
			return alert;
		}
	}
	//Help Menu
	if([identifier isEqualToString:@"scripts-option1"])
	{
		
		
		BRAlertController *alert = [BRAlertController alertOfType:0
														   titled:@"Scripts Help"
													  primaryText:@"This Now Works as a Scripts and Apps menu"
													secondaryText:@"Please read the awkwardTV wiki at http://wiki.awkwardtv.org/wiki/IScripts or read the readme included with the .tar.gz file \n IScripts version 1.2 (C) 2008 -- tomcool420"];
		return alert;
	}
	
	//Populate
	if([identifier isEqualToString:@"scripts-option2"])
	{
		BRAlertController *alert = [BRAlertController alertOfType:0
														   titled:@"Populating..."
													  primaryText:@"It is scanning your ~/Documents/Scripts/ Folder and checking for .sh files"
													secondaryText:@"WARNING: THIS WILL OVERRIDE ANY MANUALLY MADE .PLIST FILES\n By now it was done a long time ago..."];
		[NSTask launchedTaskWithLaunchPath:@"/bin/bash" arguments:[NSArray arrayWithObjects:@"/System/Library/CoreServices/Finder.app/Contents/Plugins/scripts.frappliance/Contents/Resources/we2.sh", nil]];
		return alert;
	}
	
	//Reboot
	if([identifier isEqualToString:@"scripts-option3"])
	{
		BRAlertController *alert = [BRAlertController alertOfType:0
														   titled:@"Rebooting TV..."
													  primaryText:nil
													secondaryText:nil];
		[NSTask launchedTaskWithLaunchPath:@"/bin/bash" arguments:[NSArray arrayWithObjects:@"/System/Library/CoreServices/Finder.app/Contents/Plugins/scripts.frappliance/Contents/Resources/reboot.sh",nil]];
		return alert;
	}
	
	//Cut up the string and see if it is a script
	//yaya this will be changed into prefix in next version
	NSString *typeOfString = [identifier substringToIndex:15];
	// Subsequent ifs will also be changed into else if
	if([typeOfString isEqualToString:@"scripts-appls--"])
	{
		NSString *appName = [identifier substringFromIndex:15];
		[[NSWorkspace sharedWorkspace] launchApplication:appName];
	}
	
	if([typeOfString isEqualToString:@"scripts-script-"]){
		//If it is a string, get the Filename from the identifier
		NSString *scriptName = [identifier substringFromIndex:15];
		//make the path from it
		NSString *pathToScript = [NSString stringWithFormat:@"/Users/frontrow/Documents/Scripts/%@.sh",scriptName];
		//Tell People what Script they are Launching
		
		//do the task
		NSTask *task = [[NSTask alloc] init];
		NSArray *args = [NSArray arrayWithObjects:pathToScript,nil];
		[task setArguments:args];
		[task setLaunchPath:@"/bin/bash"];
		NSPipe *outPipe = [[NSPipe alloc] init];
		
		[task setStandardOutput:outPipe];
		[task setStandardError:outPipe];
		NSFileHandle *file;
		file = [outPipe fileHandleForReading];
		
		[task launch];
		NSData *data;
		data = [ file readDataToEndOfFile];
		NSString *string;
		string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
		BRAlertController *alert = [BRAlertController alertOfType:0
														   titled:scriptName
													  primaryText:pathToScript
													secondaryText:string];
		
		
//[NSTask launchedTaskWithLaunchPath:@"/bin/bash" arguments:[NSArray arrayWithObjects:pathToScript, nil]];
	/*	NSData *data = [[outPipe fileHandleForReading]
						readDataToEndOfFile];
		NSString *aString = [[NSString alloc] initWithData:data
												  encoding:NSUTF8StringEncoding];
		filenames = [[aString componentsSeparatedByString:@"\n"] retain];
		NSLog(@"filenames = %@", filenames);
		[aString release];*/
		
		return alert;
		
		
	}
}



-(id)applianceCategories {
	

		
	NSMutableArray *categories = [NSMutableArray array];
	
	int prefor = 99;
	
	
	BRApplianceCategory *category = [BRApplianceCategory categoryWithName:[BRLocalizedStringManager appliance:self localizedStringForKey:@"Show/Hide" inFile:nil] 
																   identifier:@"scripts-option4" 
															   preferredOrder:prefor];
	
	[categories addObject:category];
	
	

		
	//Loading Builtin Scripts
	
	NSArray *loginItemDictToo = [NSArray arrayWithContentsOfFile:[NSString  stringWithFormat:@"/System/Library/CoreServices/Finder.app/Contents/Plugins/Scripts.frappliance/Contents/Resources/scripts.plist"]];
	NSEnumerator *enumeratorToo = [loginItemDictToo objectEnumerator];
	id obje;
	while((obje = [enumeratorToo nextObject]) != nil) 
	{
		BRApplianceCategory *categorytoo = [BRApplianceCategory categoryWithName:[BRLocalizedStringManager appliance:self localizedStringForKey:[obje valueForKey:@"name"] inFile:nil] 
																   identifier:[obje valueForKey:@"identifier"] 
															   preferredOrder:[[obje valueForKey:@"preferred-order"] floatValue]];
		
		[categories addObject:categorytoo];
	}
	
	
	// Add additional entries from ~/Documents/Scripts/Scripts.plist -- the scripts
	
	NSArray *loginItemDict = [NSArray arrayWithContentsOfFile:[NSString  stringWithFormat:@"/Users/frontrow/Documents/Scripts/Scripts.plist"]];
	NSEnumerator *enumerator = [loginItemDict objectEnumerator];
	
	id obj;
	NSString *idStr =@"scripts-script-";
	float current = 110;
	while((obj = [enumerator nextObject]) != nil) 
	{
		current++;
		NSString *catName = [obj valueForKey:@"name"];
		NSString *identifierIs = [idStr stringByAppendingString:catName];
		float prefOrd = [[obj valueForKey:@"preferred-order"] floatValue];
		if (prefOrd == nil)
		{
			prefOrd = current;
		}
		BRApplianceCategory *category = [BRApplianceCategory categoryWithName:[BRLocalizedStringManager appliance:self localizedStringForKey:[obj valueForKey:@"name"] inFile:nil] 
																   identifier:identifierIs
															   preferredOrder:prefOrd];
		
		[categories addObject:category];
	}
	
	// Add Additional entries for the Applications from apps.plist
	
	NSArray *AppItemArray = [NSArray arrayWithContentsOfFile:[NSString stringWithFormat:@"/Users/frontrow/Documents/Scripts/Apps.plist"]];
	NSEnumerator *appsEnum = [AppItemArray objectEnumerator];
	id obj2;
	current = 100;
	while ((obj2 = [appsEnum nextObject]) != nil)
	{
		NSString *catName= [obj2 valueForKey:@"name"];
		NSString *identifierIs =[obj2 valueForKey:@"identifier"];
		float prefOrd = [[obj valueForKey:@"preferred-order"] floatValue];
		if (prefOrd == nil)
		{
			prefOrd = current;
		}
		current++;
		BRApplianceCategory *category = [BRApplianceCategory categoryWithName:[BRLocalizedStringManager appliance:self localizedStringForKey:catName inFile:nil] 
																   identifier:identifierIs
															   preferredOrder:prefOrd];
		[categories addObject:category];
	}
	
	return categories;
}



-(id)identifierForContentAlias:(id)fp8 {
	return @"scripts-option1";
}

-(id)applianceInfo {
	return [BRApplianceInfo infoForApplianceBundle:[NSBundle bundleForClass:[self class]]];
}

//Not Used yet, probably going to go in a different class.

/*-(id)scriptsDownloader:(NSURL *) theurl
{

	NSURLRequest *theRequest = [NSURLRequest requestWithURL:theurl
												cachePolicy: NSURLRequestUseProtocolCachePolicy
											timeoutInterval: 60.0];
	NSURLDownload  *theDownload=[[NSURLDownload alloc] initWithRequest:theRequest delegate:self];
    NSString *yesOrNo=@"No";
	if (!theDownload) {
		return yesOrNo;
	}
	else
	{
		yesOrNo=@"Yes";
		return yesOrNo;
	}
}
- (void)download:(NSURLDownload *)download decideDestinationWithSuggestedFilename:(NSString *)filename
{
    NSString *destinationFilename;
    NSString *homeDirectory=NSHomeDirectory();
	
    destinationFilename=[[homeDirectory stringByAppendingPathComponent:@"Documents"]
						 stringByAppendingPathComponent:filename];
    [download setDestination:destinationFilename allowOverwrite:NO];
}
- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error
{
    // release the connection
    [download release];
	
    // inform the user
    NSLog(@"Download failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}
- (void)downloadDidFinish:(NSURLDownload *)download
{
    // release the connection
    [download release];
	
    // do something with the data
    NSLog(@"%@",@"downloadDidFinish");
}*/

@end